package nancal.mp.service

import io.kubernetes.client.openapi.ApiClient
import nancal.mp.db.mongo.extend.getAppDeploySetting
import nancal.mp.db.mongo.mor
import nbcp.base.extend.HasValue
import org.springframework.boot.context.event.ApplicationReadyEvent
import org.springframework.context.event.EventListener
import org.springframework.stereotype.Service

@Service
abstract class K8sBaseService {
    companion object {

        fun getK8sClient(env: String): ApiClient {
            /**
             * cat ~/.kube/config
             */

            /**
             * 本地调试，需要添加 host
             * 192.168.5.213 k8s-master01
             */

            var deploySetting = mor.dev.appDeploySetting.getAppDeploySetting(env)


            if (deploySetting.k8sConfig.apiServerUrl.HasValue &&
                deploySetting.k8sConfig.apiToken.HasValue
            ) {
                var api = ApiClient();
                api.basePath = deploySetting.k8sConfig.apiServerUrl
                api.setApiKey(deploySetting.k8sConfig.apiToken);
                api.setApiKeyPrefix("Bearer")
                api.isVerifyingSsl = false;
                return api;
            }

//            if (deploySetting.k8sConfig.kubeConfigContent.HasValue) {
//
//                return ClientBuilder.kubeconfig(KubeConfig.loadKubeConfig(deploySetting.k8sConfig.kubeConfigContent.reader()))
//                    .build()
//            }

            throw RuntimeException("找不到K8s配置项 ${deploySetting.code} 的认证内容")
        }

        fun initDefaultK8sEnv() {
            io.kubernetes.client.openapi.Configuration.setDefaultApiClient(getK8sClient(""))
        }
    }


    @EventListener
    fun start(event: ApplicationReadyEvent) {
        //不进行自动注入，因为其它环境可能没有配置数据表。
    }
}